package cn.ehanghai.htz.client;

import cn.ehanghai.htz.common.utils.AisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @Author: xumf
 * @Date: 2019/6/21 16:02
 */
@Slf4j
@Configuration
public class TcpClient {

//    private static final String ip="192.168.20.39";
    private static final String ip="202.118.80.110";//浙海大固定ip地址
    private static final int port=8888;//浙海大的socket 端口
//    private static final int port=7777;

    private static Socket socket;
    private static Boolean readFlag=true;
//    private boolean close = false; // 关闭连接标志位，true表示关闭，false表示连接

    public static Socket getInstance(String ip,Integer port) {
        if(socket==null){
            try {
                socket=new Socket(ip,port);
            } catch (IOException e) {
                System.out.println("未连接到服务器");
                return null;
            }
        }
        return socket;
    }

    public static Socket getSocket() {
        return socket;
    }

    public static void setSocket(Socket socket) {
        TcpClient.socket = socket;
    }

    public static void setReadFlag(Boolean readFlag) {
        TcpClient.readFlag = readFlag;
    }

    public static Boolean getReadFlag() {
        return readFlag;
    }

    public static void main(String[] args) {
        if(getInstance(ip,port)!=null) {
            new TcpClient().socketTest();
        }
    }

    public   void socketTest(){
        try {

            //1
//            socket=new Socket(ip,port);
            //2
//            OutputStream os=socket.getOutputStream();
//            PrintWriter pw=new PrintWriter(os);
//            pw.write("你好，我是海图桌");
//            pw.flush();
//            socket.shutdownOutput();
            //3

            InputStream is=socket.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            String info=null;
            int count=0;

            while ((info=br.readLine())!=null&&readFlag){
                log.warn("接受服务器数据第{}：",count+"信息内容--{}",info);
                AisUtil.parsingAis(info);
                count++;
             }
             br.close();
             is.close();
//           pw.close();
//           os.close();
//           socket.close();

        } catch (IOException e) {
            System.out.println("socket 服务器未启动");
            e.printStackTrace();

        }
    }

    public  boolean isServerClose(Socket socket){
        try {
            socket.sendUrgentData(0xFF);
            return false;
        } catch (IOException e) {
//            e.printStackTrace();
            return true;
        }

    }


}
